<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>病人分配系统</title>
<style>
/* 页面整体 */
body {
  font-family: "Tahoma", Tahoma, Geneva, Verdana, sans-serif;
  font-size: 2rem;
  background: #f4f6f8;
  margin: 0;
  padding: 1rem;
  color: #333;
}

/* 标题 */
h1 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 0.5rem;
  font-size: 3rem;
}

h2 {
  color: #34495e;
  margin-top: 1rem;
  margin-bottom: 0.5rem;
  display: inline-block;
  font-size: 2.2rem;
}

#settingsGear {
  cursor: pointer;
  font-size: 2rem;
    margin-bottom: : 0.5rem;
  vertical-align: middle;
}

/* 输入区域 */
div input[type="text"], div input[list] {
  padding: 0.6rem 0.8rem;
  margin-bottom: 0.6rem;
  border-radius: 0.6rem;
  border: 0.1rem solid #ccc;
  outline: none;
  font-size: 2rem;
  width: 100%;
  max-width: 20rem;
}

div input:focus {
  border-color: #3498db;
  box-shadow: 0 0 0.3rem rgba(52,152,219,0.4);
}

/* 按钮 */
button {
  padding: 0.6rem 1rem;
  border: none;
  border-radius: 0.6rem;
  cursor: pointer;
  font-weight: bold;
  background-color: #3498db;
  color: white;
  font-size: 2rem;
  transition: background-color 0.2s;
}

button:hover {
  background-color: #2980b9;
}

/* 切换视图按钮 */
.switchView {
  margin-top: 0.5rem;
}

.switchView button {
  background-color: #ecf0f1;
  color: #2c3e50;
}

.switchView button:hover {
  background-color: #bdc3c7;
}

/* 容器布局 */
.container {
  display: grid;
  gap: 1rem;
  margin-top: 1rem;
}

/* 医生列 */
.column-container {
  background: #ffffff;
  padding: 1rem;
  border-radius: 1rem;
  min-width: 16rem;
  box-shadow: 0 0.4rem 1.2rem rgba(0,0,0,0.08);
}

.column-container h3 {
  text-align: center;
  margin-bottom: 0.5rem;
  cursor: pointer;
  color: #2c3e50;
  font-size: 2rem;
}

/* 病人卡片 */
.patient {
  background: #d0eaff;
  margin: 0.5rem 0;
  padding: 1rem;
  border-radius: 0.6rem;
  cursor: pointer;
  transition: background-color 0.2s, transform 0.1s;
  user-select: none;
  font-size: 2rem;
}

.patient:hover {
  background-color: #a9d6ff;
}

.patient.recent {
  background-color: #b6f1b0 !important;
}

/* 操作区 */
.operations {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-top: 1rem;
}

.op-cell {
  background: #ffdede;
  padding: 1rem;
  border-radius: 0.8rem;
  flex: 1 1 10rem;
  text-align: center;
  font-weight: bold;
  cursor: grab;
  font-size: 2rem;
  transition: background-color 0.2s;
}

.op-cell:hover {
  background-color: #ffbaba;
}

/* 模态框 */
.modal-bg {
  position: fixed;
  top:0; left:0;
  width:100%; height:100%;
  background: rgba(0,0,0,0.5);
  display: none;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.modal {
  background: #fff;
  padding: 2rem;
  border-radius: 1.2rem;
  min-width: 28rem;
  max-width: 90%;
  box-shadow: 0 0.8rem 2rem rgba(0,0,0,0.15);
  font-size: 2rem;
}

.modal input {
  width: 100%;
  padding: 0.8rem 1rem;
  margin-bottom: 1rem;
  border-radius: 0.6rem;
  border: 0.1rem solid #ccc;
  font-size: 2rem;
}

.modal button {
  width: 48%;
  margin-right: 4%;
  font-size: 2rem;
}

.modal button:last-child {
  margin-right: 0;
  background-color: #95a5a6;
}

/* 页脚 */
div[style*="text-align: center"] {
  color: #95a5a6;
  font-size: 2rem;
  margin-top: 2rem;
}

/* ===== 响应式布局 ===== */

/* 手机（小屏 < 600px）：一列布局 */
@media (max-width: 600px) {
  .container {
    grid-template-columns: 1fr;
  }
  .patient {
    font-size: 2rem;
    padding: 1.2rem;
  }
  .operations {
    flex-direction: column;
  }
  .op-cell {
    flex: 1 1 auto;
  }
}

/* 平板（中屏 600-900px）：两列布局 */
@media (min-width: 600px) and (max-width: 900px) {
  .container {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* 电脑（大屏 > 900px）：多列自适应 */
@media (min-width: 900px) {
  .container {
    grid-template-columns: repeat(auto-fill, minmax(20rem, 1fr));
  }
}
</style>




  
</head>
<body>
<h1 style="text-align: center;">创二病人分配系统</h2>
<h2>病人录入</h2>

<div>
  <input type="text" id="patientName" placeholder="病人姓名">
  <input list="doctorList" id="doctorInput" placeholder="选择或输入医生">
  <datalist id="doctorList"></datalist>
  <button id="addPatientBtn">添加病人</button>
</div>

<h2>病人列表</h2>
<span id="settingsGear">⚙️</span>

<div class="switchView" style="display:inline;">
  <button id="currentBtn">当前在院</button>
  <button id="allBtn">所有病人</button>
</div>
  
<div class="container" id="columnsContainer"></div>
  
<div class="operations">
  <div class="op-cell" id="dischargeCell">出院</div>
  <div class="op-cell" id="deleteCell">删除</div>
</div>

<!-- 模态框 -->
<div class="modal-bg" id="modalBg">
  <div class="modal">
    <label id="modalLabel"></label>
    <input type="text" id="modalInput">
    <div style="text-align:right;">
      <button id="modalConfirm">确认</button>
      <button id="modalCancel">取消</button>
    </div>
  </div>
</div>

<div style="text-align: center;margin:18px;">©Aoyama</div>




  
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/12.3.0/firebase-app.js";
import { getDatabase, ref, set, onValue } from "https://www.gstatic.com/firebasejs/12.3.0/firebase-database.js";

const firebaseConfig = {
  apiKey: "AIzaSyCe5seH8kOkGOfquiUYvFHz2bvcDssWGMs",
  authDomain: "patient-reminder-95c8d.firebaseapp.com",
  databaseURL: "https://patient-reminder-95c8d-default-rtdb.firebaseio.com",
  projectId: "patient-reminder-95c8d",
  storageBucket: "patient-reminder-95c8d.firebasestorage.app",
  messagingSenderId: "726326025491",
  appId: "1:726326025491:web:6b77dce30f7c0f9ddc4ee6"
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);

let patients=[], doctors=[], recentPatientName=null, showAll=false;
let editPatient=null;

// 模态框操作
const modalBg=document.getElementById("modalBg");
const modalInput=document.getElementById("modalInput");
const modalLabel=document.getElementById("modalLabel");
const modalConfirm=document.getElementById("modalConfirm");
const modalCancel=document.getElementById("modalCancel");

function openModal(label,text,callback){
  modalLabel.innerText=label;
  modalInput.value=text;
  modalBg.style.display="flex";
  modalInput.focus();
  const confirmHandler=()=>{ callback(modalInput.value.trim()); closeModal(); };
  modalConfirm.onclick=confirmHandler;
  modalCancel.onclick=()=>{ closeModal(); };
  function closeModal(){ modalBg.style.display="none"; modalConfirm.onclick=null; modalCancel.onclick=null; }
}

// 渲染医生列
function renderColumns(){
  let displayPatients=showAll ? patients : patients.filter(p=>!p.discharge);
  doctors=doctors.filter(doc=>displayPatients.some(p=>p.doctor===doc));
  displayPatients.forEach(p=>{ if(p.row===undefined || p.row===null)p.row=0; });

  const container=document.getElementById("columnsContainer");
  container.innerHTML="";
  doctors.forEach(doc=>{
    const colDiv=document.createElement("div");
    colDiv.className="column-container";
    colDiv.dataset.doctor=doc;

    const header=document.createElement("h3");
    header.innerText=doc;
    header.addEventListener("click",()=>{ 
      openModal("修改医生姓名",doc,newName=>{
        if(newName && newName!==doc){
          patients.forEach(p=>{ if(p.doctor===doc)p.doctor=newName; });
          const idx=doctors.indexOf(doc); if(idx>-1) doctors[idx]=newName;
          set(ref(db,'patients'),patients);
          set(ref(db,'doctorOrder'),doctors);
          renderColumns();
        }
      });
    });
    colDiv.appendChild(header);

    displayPatients.filter(p=>p.doctor===doc).sort((a,b)=>a.row-b.row)
    .forEach((p,index)=>{
      p.row=index;
      const pDiv=document.createElement("div");
      pDiv.className="patient";
      if(p.name===recentPatientName)pDiv.classList.add("recent");
      if(showAll && p.discharge)pDiv.innerText=p.name+" (已出院)"; else pDiv.innerText=p.name;
      pDiv.draggable=true;
      pDiv.dataset.name=p.name;
      pDiv.dataset.doctor=p.doctor;
      pDiv.dataset.row=p.row;

      // 点击编辑姓名
      pDiv.addEventListener("click",()=>{
        editPatient=p;
        openModal("修改病人姓名",p.name,newName=>{
          if(newName && newName!==p.name){
            p.name=newName;
            // 不改变 recentPatientName
            set(ref(db,'patients'),patients);
            renderColumns();
          }
        });
      });
      colDiv.appendChild(pDiv);
    });
    container.appendChild(colDiv);
  });
  updateDoctorList();
}

// 更新医生列表
function updateDoctorList(){
  const list=document.getElementById("doctorList");
  list.innerHTML=doctors.map(d=>`<option value="${d}">`).join("");
}

// 添加病人
document.getElementById("addPatientBtn").addEventListener("click",()=>{
  const name=document.getElementById("patientName").value.trim();
  const doctor=document.getElementById("doctorInput").value.trim();
  if(!name || !doctor) return alert("请输入姓名并选择医生");
  if(!doctors.includes(doctor)) doctors.push(doctor);

  const colPatients=patients.filter(p=>p.doctor===doctor && !p.discharge);
  const row=colPatients.length ?? 0;
  const newPatient={name,doctor,row};
  patients.push(newPatient);

  // ✅ 仅添加新病人时更新 recentPatientName
  recentPatientName=name;

  updateFirebase();
  set(ref(db,'recentPatientName'), recentPatientName);

  document.getElementById("patientName").value="";
  document.getElementById("doctorInput").value="";
  renderColumns();
});

// Firebase 同步
function updateFirebase(){
  set(ref(db,'patients'),patients);
  set(ref(db,'doctorOrder'),doctors);
  // recentPatientName 只在添加新病人时更新
}

// 同步 patients 数据
onValue(ref(db,'patients'),snapshot=>{
  patients=snapshot.val()||[];
  renderColumns();
});
// 同步医生顺序
onValue(ref(db,'doctorOrder'),snapshot=>{
  const cloudOrder=snapshot.val();
  if(cloudOrder) doctors=cloudOrder;
  renderColumns();
});
// 同步最近添加病人
onValue(ref(db,'recentPatientName'), snapshot => {
  recentPatientName = snapshot.val() || null;
  renderColumns();
});

// 设置医生顺序
document.getElementById("settingsGear").addEventListener("click",()=>{
  openModal("设置医生顺序（用 - 分割）",doctors.join("-"),val=>{
    if(val){
      const newOrder=val.split("-").map(d=>d.trim()).filter(d=>d);
      doctors=newOrder;
      set(ref(db,'doctorOrder'),doctors);
      renderColumns();
    }
  });
});

// 切换视图
document.getElementById("currentBtn").addEventListener("click",()=>{ showAll=false; renderColumns(); });
document.getElementById("allBtn").addEventListener("click",()=>{ showAll=true; renderColumns(); });

// 拖拽病人与操作
let dragPatient=null;
document.addEventListener("dragstart",e=>{
  const p=e.target.closest(".patient");
  if(p) dragPatient=p;
});
document.addEventListener("dragover",e=>e.preventDefault());
document.addEventListener("drop",e=>{
  e.preventDefault();
  const targetCol = e.target.closest(".column-container");
  const targetPatient = e.target.closest(".patient");
  const opCell = e.target.closest(".op-cell");

  if(dragPatient && targetCol){
    const targetDoctor=targetCol.dataset.doctor;
    const patientObj=patients.find(p=>p.name===dragPatient.dataset.name);
    if(!patientObj) return;

    if(targetPatient && targetPatient!==dragPatient){
      const targetObj=patients.find(p=>p.name===targetPatient.dataset.name);
      if(targetObj){ const temp=patientObj.row ??0; patientObj.row=targetObj.row ??0; targetObj.row=temp; }
    }else{
      patientObj.doctor=targetDoctor;
      const colPatients=patients.filter(p=>p.doctor===targetDoctor && !p.discharge);
      patientObj.row=colPatients.length ??0;
    }
    updateFirebase();
    dragPatient=null;
    renderColumns();
    return;
  }

  if(dragPatient && opCell){
    const patientIndex=patients.findIndex(p=>p.name===dragPatient.dataset.name);
    if(patientIndex>-1){
      if(opCell.id==="deleteCell"){ patients.splice(patientIndex,1); }
      else if(opCell.id==="dischargeCell"){ patients[patientIndex].discharge=true; }
      updateFirebase();
      dragPatient=null;
      renderColumns();
    }
  }
});
</script>

</body>
</html>
